package com.yuxi.service;

import com.yuxi.constants.DataType;
import com.yuxi.constants.MyException;
import com.yuxi.datasource.DynamicDataSource;
import com.yuxi.mapper.UserMapper;
import com.yuxi.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by yuxi on 16/10/24.
 */
@Service
public class UserService {
    @Autowired
    private User user;

    public User getUser(String name, String password) {
        return new User(name, password);
    }

    public void setUser(User user) {
        this.user = user;
    }


    @Autowired
    private UserMapper userMapper;

    public boolean addUser(String username, String password) {
        return userMapper.insertUser(username, password) == 1 ? true : false;
    }

    public User addUserWithBackId(String username, String password) {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userMapper.insertUserWithBackId(user);//该方法后，主键已经设置到user中了
        return user;
    }

    public List<User> getUserList() {
        DynamicDataSource.DataBaseContextHolder.setDataType(DataType.JIUYE);
        List<User> users = userMapper.getUserList();
        return  users;
    }

    public boolean delete(String username) {
        return userMapper.delete(username);
    }

    @Transactional
    public void testTransaction(String username, String password) {
        System.out.println(userMapper.insertUser(username, password));
        testTransactional(username);
    }

    public void testTransactional(String username) {
        System.out.println(username);
        throw new MyException("测试事务");
    }
}
